<template>
  <div class="map-wrap">
    <div class="map" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { Map, MapStyle, Marker, config } from '@maptiler/sdk';
import {shallowRef, onMounted, onUnmounted, markRaw, ref} from 'vue';
import '@maptiler/sdk/dist/maptiler-sdk.css';
import { listLocation } from '@/api/insect/location'
import {ElMessage} from "element-plus";

// 新增状态用于存储位置数据
const locations = ref([])
const mapContainer = shallowRef(null);
const map = shallowRef(null);

onMounted(async () => {
  // 先获取位置数据
  try {
    const res = await listLocation({
      page: 1,
      size: 100,  // 确保获取全部数据
      keyword: ''
    })
    if (res.code === 200) {
      locations.value = res.data.list
    }
  } catch (error) {
    ElMessage.error('获取位置数据失败')
  }

  // 初始化地图
  config.apiKey = 'b7iBKrW38JRV8sYcMw50'
  map.value = markRaw(new Map({
    container: mapContainer.value,
    style: MapStyle.HYBRID, // 地图样式
    center: [118.0567, 24.6176],  // 初始位置
    zoom: 15
  }));

  // 动态添加标记
  map.value.on('load', () => {
    locations.value.forEach(loc => {
      new Marker({ color: "#FF0000" })
        .setLngLat([loc.longitude, loc.latitude])
        .addTo(map.value)
    })
  })
})
</script>

<style scoped>
.map-wrap {
  position: relative;
  width: 100%;
  height: calc(100vh - 105px);
}

.map {
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>
